package com.riche.codefactory.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.riche.codefactory.annotation.AuthCheck;
import com.riche.codefactory.common.BaseResponse;
import com.riche.codefactory.common.DeleteRequest;
import com.riche.codefactory.common.ErrorCode;
import com.riche.codefactory.common.R;
import com.riche.codefactory.constant.UserConstant;
import com.riche.codefactory.exception.BusinessException;
import com.riche.codefactory.exception.ThrowUtils;
import com.riche.codefactory.model.c2s.questionBankQuestion.*;
import com.riche.codefactory.model.domain.QuestionBankQuestion;
import com.riche.codefactory.model.domain.User;
import com.riche.codefactory.model.s2c.S2cQuestionBankQuestion;
import com.riche.codefactory.service.IQuestionBankQuestionSVC;
import com.riche.codefactory.service.IUserSVC;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 题库题目关联接口
 *
 */
@RestController
@RequestMapping("/questionBankQuestion")
@Slf4j
public class QuestionBankQuestionController {

    @Resource
    private IQuestionBankQuestionSVC IQuestionBankQuestionSVC;

    @Resource
    private IUserSVC userService;

    // region 增删改查

    /**
     * 创建题库题目关联
     *
     * @param c2sQuestionBankQuestionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestionBankQuestion(@RequestBody C2sQuestionBankQuestionAddRequest c2sQuestionBankQuestionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankQuestionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        BeanUtils.copyProperties(c2sQuestionBankQuestionAddRequest, questionBankQuestion);
        // 数据校验
        IQuestionBankQuestionSVC.validQuestionBankQuestion(questionBankQuestion, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        questionBankQuestion.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = IQuestionBankQuestionSVC.save(questionBankQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionBankQuestionId = questionBankQuestion.getId();
        return R.ok(newQuestionBankQuestionId);
    }

    /**
     * 删除题库题目关联
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestionBankQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionBankQuestion oldQuestionBankQuestion = IQuestionBankQuestionSVC.getById(id);
        ThrowUtils.throwIf(oldQuestionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionBankQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = IQuestionBankQuestionSVC.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 更新题库题目关联（仅管理员可用）
     *
     * @param c2sQuestionBankQuestionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionBankQuestion(@RequestBody C2sQuestionBankQuestionUpdateRequest c2sQuestionBankQuestionUpdateRequest) {
        if (c2sQuestionBankQuestionUpdateRequest == null || c2sQuestionBankQuestionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionBankQuestion questionBankQuestion = new QuestionBankQuestion();
        BeanUtils.copyProperties(c2sQuestionBankQuestionUpdateRequest, questionBankQuestion);
        // 数据校验
        IQuestionBankQuestionSVC.validQuestionBankQuestion(questionBankQuestion, false);
        // 判断是否存在
        long id = c2sQuestionBankQuestionUpdateRequest.getId();
        QuestionBankQuestion oldQuestionBankQuestion = IQuestionBankQuestionSVC.getById(id);
        ThrowUtils.throwIf(oldQuestionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = IQuestionBankQuestionSVC.updateById(questionBankQuestion);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return R.ok(true);
    }

    /**
     * 根据 id 获取题库题目关联（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<S2cQuestionBankQuestion> getQuestionBankQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        QuestionBankQuestion questionBankQuestion = IQuestionBankQuestionSVC.getById(id);
        ThrowUtils.throwIf(questionBankQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return R.ok(IQuestionBankQuestionSVC.getQuestionBankQuestionVO(questionBankQuestion, request));
    }

    /**
     * 分页获取题库题目关联列表（仅管理员可用）
     *
     * @param c2sQuestionBankQuestionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionBankQuestion>> listQuestionBankQuestionByPage(@RequestBody C2sQuestionBankQuestionQueryRequest c2sQuestionBankQuestionQueryRequest) {
        long current = c2sQuestionBankQuestionQueryRequest.getCurrent();
        long size = c2sQuestionBankQuestionQueryRequest.getPageSize();
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = IQuestionBankQuestionSVC.page(new Page<>(current, size),
                IQuestionBankQuestionSVC.getQueryWrapper(c2sQuestionBankQuestionQueryRequest));
        return R.ok(questionBankQuestionPage);
    }

    /**
     * 分页获取题库题目关联列表（封装类）
     *
     * @param c2sQuestionBankQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<S2cQuestionBankQuestion>> listQuestionBankQuestionVOByPage(@RequestBody C2sQuestionBankQuestionQueryRequest c2sQuestionBankQuestionQueryRequest,
                                                                                        HttpServletRequest request) {
        long current = c2sQuestionBankQuestionQueryRequest.getCurrent();
        long size = c2sQuestionBankQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = IQuestionBankQuestionSVC.page(new Page<>(current, size),
                IQuestionBankQuestionSVC.getQueryWrapper(c2sQuestionBankQuestionQueryRequest));
        // 获取封装类
        return R.ok(IQuestionBankQuestionSVC.getQuestionBankQuestionVOPage(questionBankQuestionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题库题目关联列表
     *
     * @param c2sQuestionBankQuestionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<S2cQuestionBankQuestion>> listMyQuestionBankQuestionVOByPage(@RequestBody C2sQuestionBankQuestionQueryRequest c2sQuestionBankQuestionQueryRequest,
                                                                                          HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankQuestionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        c2sQuestionBankQuestionQueryRequest.setUserId(loginUser.getId());
        long current = c2sQuestionBankQuestionQueryRequest.getCurrent();
        long size = c2sQuestionBankQuestionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionBankQuestion> questionBankQuestionPage = IQuestionBankQuestionSVC.page(new Page<>(current, size),
                IQuestionBankQuestionSVC.getQueryWrapper(c2sQuestionBankQuestionQueryRequest));
        // 获取封装类
        return R.ok(IQuestionBankQuestionSVC.getQuestionBankQuestionVOPage(questionBankQuestionPage, request));
    }


    /**
     * 删除题库题目关联
     *
     * @param c2sQuestionBankQuestionRemoveRequest
     * @param request
     * @return
     */
    @PostMapping("/remove")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> removeQuestionBankQuestion(@RequestBody C2sQuestionBankQuestionRemoveRequest c2sQuestionBankQuestionRemoveRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankQuestionRemoveRequest == null, ErrorCode.PARAMS_ERROR);
        User user = userService.getLoginUser(request);
        Long questionBanId = c2sQuestionBankQuestionRemoveRequest.getQuestionBanId();
        Long questionId = c2sQuestionBankQuestionRemoveRequest.getQuestionId();
        LambdaQueryWrapper<QuestionBankQuestion> queryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                .eq(QuestionBankQuestion::getQuestionId, questionId)
                .eq(QuestionBankQuestion::getQuestionBankId, questionBanId);
        boolean result = IQuestionBankQuestionSVC.remove(queryWrapper);
        return R.ok(result);
    }

    /**
     * 批量添加题目到题库
     *
     * @param questionBankQuestionBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/add/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchAddQuestionsToBank(@RequestBody C2sQuestionBankQuestionBatchAddRequest questionBankQuestionBatchRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionBankQuestionBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Long questionBankId = questionBankQuestionBatchRequest.getQuestionBankId();
        List<Long> questionIdList = questionBankQuestionBatchRequest.getQuestionIdList();
        IQuestionBankQuestionSVC.batchAddQuestionToBank(questionIdList, questionBankId, loginUser);
        return R.ok(true);
    }

    /**
     * 批量从题库移除题目
     *
     * @param c2sQuestionBankQuestionBatchRemoveRequest
     * @param request
     * @return
     */
    @PostMapping("/remove/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> batchRemoveQuestionsToBank(@RequestBody C2sQuestionBankQuestionBatchRemoveRequest c2sQuestionBankQuestionBatchRemoveRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(c2sQuestionBankQuestionBatchRemoveRequest == null, ErrorCode.PARAMS_ERROR);
        Long questionBankId = c2sQuestionBankQuestionBatchRemoveRequest.getQuestionBankId();
        List<Long> questionIdList = c2sQuestionBankQuestionBatchRemoveRequest.getQuestionIdList();
        IQuestionBankQuestionSVC.batchRemoveQuestionToBank(questionIdList, questionBankId);
        return R.ok(true);
    }

    // endregion
}
